<template>
  <div class="my-resumes-container">
    <el-row :gutter="20">
      <!-- 左侧：创建的简历 -->
      <el-col :span="12">
        <div class="resume-section">
          <div class="section-header">
            <h2>创建的简历 ({{ totalCreated }})</h2>
            <el-button type="primary" @click="createNewResume">
              <el-icon><Plus /></el-icon>
              新建简历
            </el-button>
          </div>
          
          <div class="resume-list-container" v-if="createdResumes.length > 0">
            <div class="resume-list">
              <ResumeCard
                v-for="resume in paginatedCreatedResumes"
                :key="resume.id"
                :resume-id="resume.id"
                :title="resume.resume_name"
                :date="formatDate(resume.updated_at)"
                :is-shared="resume.is_shared === 1"
                @refresh="loadResumeList"
              />
            </div>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="createdCurrentPage"
                :page-size="createdPageSize"
                :total="totalCreated"
                layout="prev, pager, next"
                :hide-on-single-page="true"
                @current-change="handleCreatedPageChange"
              />
            </div>
          </div>
          
          <el-empty 
            v-else 
            description="暂无创建的简历"
            :image-size="150"
          >
            <el-button type="primary" @click="createNewResume">
              立即创建
            </el-button>
          </el-empty>
        </div>
      </el-col>
      
      <!-- 右侧：上传的PDF简历 -->
      <el-col :span="12">
        <div class="resume-section">
          <div class="section-header">
            <h2>上传的简历 ({{ totalUploaded }})</h2>
            <el-button type="primary" @click="handleUpload">
              <el-icon><Upload /></el-icon>
              上传简历
            </el-button>
          </div>
          
          <div class="resume-list-container" v-if="uploadedResumes.length > 0">
            <div class="pdf-resume-grid">
              <div 
                v-for="resume in paginatedUploadedResumes" 
                :key="resume.id"
                class="pdf-resume-card"
              >
                <div class="pdf-card-header">
                  <div class="pdf-icon">
                    <el-icon><Document /></el-icon>
                  </div>
                  <div class="pdf-actions-icon">
                    <el-tooltip content="预览" placement="top">
                      <el-button 
                        circle 
                        size="small" 
                        @click="previewPDF(resume)"
                        class="action-icon-btn"
                      >
                        <el-icon><View /></el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="下载" placement="top">
                      <el-button 
                        circle 
                        size="small" 
                        @click="downloadPDF(resume)"
                        class="action-icon-btn"
                      >
                        <el-icon><Download /></el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                      <el-button 
                        circle 
                        size="small" 
                        type="danger"
                        @click.stop="deleteUploadedResume(resume.id)"
                        class="action-icon-btn"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                </div>
                <div class="pdf-card-body" @click="previewPDF(resume)">
                  <h3 class="pdf-title" :title="resume.file_name">{{ resume.file_name }}</h3>
                  <p class="pdf-meta">{{ formatFileSize(resume.file_size) }}</p>
                  <p class="pdf-date">{{ formatDate(resume.created_at) }}</p>
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="uploadedCurrentPage"
                :page-size="uploadedPageSize"
                :total="totalUploaded"
                layout="prev, pager, next"
                :hide-on-single-page="true"
                @current-change="handleUploadedPageChange"
              />
            </div>
          </div>
          
          <el-empty 
            v-else 
            description="暂无上传的简历"
            :image-size="150"
          >
            <el-button type="primary" @click="handleUpload">
              立即上传
            </el-button>
          </el-empty>
        </div>
      </el-col>
    </el-row>
    
    <!-- 上传对话框 -->
    <el-dialog 
      v-model="uploadDialogVisible" 
      title="上传简历" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        class="upload-area"
        drag
        :auto-upload="false"
        :limit="1"
        accept=".pdf"
        :on-change="handleFileChange"
        :on-exceed="handleExceed"
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          将PDF文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只支持 PDF 格式，文件大小不超过 10MB
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploading">
          确定上传
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Upload, UploadFilled, Document, View, Download, Delete } from '@element-plus/icons-vue';
import instance from '@/utils/request';
import ResumeCard from '@/components/ResumeCard.vue';

const router = useRouter();

// 数据
const createdResumes = ref([]);
const uploadedResumes = ref([]);
const uploadDialogVisible = ref(false);
const uploading = ref(false);
const uploadRef = ref(null);
const currentFile = ref(null);


// 分页相关 - 创建的简历
const createdCurrentPage = ref(1);
const createdPageSize = ref(6); // 每页显示6条（2列，每列3条）
const totalCreated = computed(() => createdResumes.value.length);

// 分页相关 - 上传的简历
const uploadedCurrentPage = ref(1);
const uploadedPageSize = ref(12); // 每页显示12条（自适应列数）
const totalUploaded = computed(() => uploadedResumes.value.length);

// 计算属性 - 创建的简历分页数据
const paginatedCreatedResumes = computed(() => {
  const start = (createdCurrentPage.value - 1) * createdPageSize.value;
  const end = start + createdPageSize.value;
  return createdResumes.value.slice(start, end);
});

// 计算属性 - 上传的简历分页数据
const paginatedUploadedResumes = computed(() => {
  const start = (uploadedCurrentPage.value - 1) * uploadedPageSize.value;
  const end = start + uploadedPageSize.value;
  return uploadedResumes.value.slice(start, end);
});

// 加载创建的简历列表
const loadResumeList = async () => {
  try {
    console.log('📥 开始加载简历列表...');
    const response = await instance.request({
      method: 'GET',
      url: '/resumes'
    });
    console.log('📦 后端响应:', response);
    
    if (response.code === 0) {
      // 后端返回的是分页数据，简历列表在 data.list 中
      createdResumes.value = response.data.list || [];
      console.log('✅ 简历列表加载成功，数量:', createdResumes.value.length);
      console.log('📋 简历列表:', createdResumes.value);
      
      // 如果当前页超出范围，重置为第一页
      const maxPage = Math.ceil(createdResumes.value.length / createdPageSize.value);
      if (createdCurrentPage.value > maxPage && maxPage > 0) {
        createdCurrentPage.value = 1;
      }
    } else {
      console.error('❌ 后端返回错误:', response.msg);
      ElMessage.error(response.msg || '加载简历列表失败');
    }
  } catch (error) {
    console.error('❌ 加载简历列表失败:', error);
    ElMessage.error('加载简历列表失败');
  }
};

// 加载上传的PDF简历列表
const loadUploadedResumes = async () => {
  try {
    console.log('📥 开始加载上传的PDF简历列表...');
    const response = await instance.request({
      method: 'GET',
      url: '/pdf-resumes'
    });
    console.log('📦 PDF简历后端响应:', response);
    
    if (response.code === 0) {
      uploadedResumes.value = response.data.list || [];
      console.log('✅ PDF简历列表加载成功，数量:', uploadedResumes.value.length);
      
      // 如果当前页超出范围，重置为第一页
      const maxPage = Math.ceil(uploadedResumes.value.length / uploadedPageSize.value);
      if (uploadedCurrentPage.value > maxPage && maxPage > 0) {
        uploadedCurrentPage.value = 1;
      }
    } else {
      console.error('❌ 后端返回错误:', response.msg);
      ElMessage.error(response.msg || '加载PDF简历列表失败');
    }
  } catch (error) {
    console.error('❌ 加载PDF简历列表失败:', error);
    ElMessage.error('加载PDF简历列表失败');
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
};

// 分页处理 - 创建的简历
const handleCreatedPageChange = (page) => {
  createdCurrentPage.value = page;
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 分页处理 - 上传的简历
const handleUploadedPageChange = (page) => {
  uploadedCurrentPage.value = page;
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 创建新简历
const createNewResume = () => {
  router.push('/editor');
};

// 处理上传
const handleUpload = () => {
  uploadDialogVisible.value = true;
  currentFile.value = null;
};

// 文件改变
const handleFileChange = (file) => {
  // 检查文件大小（10MB）
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过 10MB');
    uploadRef.value.clearFiles();
    return;
  }
  
  // 检查文件类型
  if (!file.name.endsWith('.pdf')) {
    ElMessage.error('只支持 PDF 格式文件');
    uploadRef.value.clearFiles();
    return;
  }
  
  currentFile.value = file;
};

// 超过限制
const handleExceed = () => {
  ElMessage.warning('一次只能上传一个文件');
};

// 提交上传
const submitUpload = async () => {
  if (!currentFile.value) {
    ElMessage.warning('请选择要上传的文件');
    return;
  }
  
  uploading.value = true;
  
  try {
    const formData = new FormData();
    formData.append('file', currentFile.value.raw);
    
    const response = await instance.request({
      method: 'POST',
      url: '/pdf-resumes/upload',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    if (response.code === 0) {
      ElMessage.success('上传成功');
      uploadDialogVisible.value = false;
      uploadRef.value.clearFiles();
      currentFile.value = null;
      
      // 重新加载列表
      await loadUploadedResumes();
    } else {
      ElMessage.error(response.msg || '上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error(error.msg || '上传失败');
  } finally {
    uploading.value = false;
  }
};

// 预览PDF
const previewPDF = (resume) => {
  // 在新窗口打开PDF
  const pdfUrl = `http://localhost:7001${resume.file_url}`;
  window.open(pdfUrl, '_blank');
};

// 下载PDF
const downloadPDF = (resume) => {
  const pdfUrl = `http://localhost:7001${resume.file_url}`;
  const link = document.createElement('a');
  link.href = pdfUrl;
  link.download = resume.file_name;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  ElMessage.success('开始下载');
};

// 删除上传的简历
const deleteUploadedResume = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这份简历吗？此操作不可恢复！', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await axios.delete(`http://localhost:7001/api/pdf-resumes/${id}`);
    
    if (response.data.code === 0) {
      ElMessage.success('删除成功');
      await loadUploadedResumes();
    } else {
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error(error.response?.data?.msg || '删除失败');
    }
  }
};

// 页面加载
onMounted(() => {
  loadResumeList();
  loadUploadedResumes();
});
</script>

<style scoped>
.my-resumes-container {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.resume-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  height: calc(100vh - 100px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.section-header {
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f0f0;
}

.section-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.resume-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.resume-list {
  flex: 1;
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
  overflow-y: auto;
  padding-right: 8px;
}

/* 自定义滚动条 */
.resume-list::-webkit-scrollbar {
  width: 6px;
}

.resume-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.resume-list::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.resume-list::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.pagination-container {
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  padding-top: 20px;
  margin-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* PDF简历网格布局 - 紧凑卡片式 */
.pdf-resume-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 8px;
  overflow-y: auto;
  flex: 1;
  align-content: flex-start;
}

/* 自定义滚动条 - PDF区域 */
.pdf-resume-grid::-webkit-scrollbar {
  width: 6px;
}

.pdf-resume-grid::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.pdf-resume-grid::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.pdf-resume-grid::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* PDF简历卡片 - 小卡片样式 */
.pdf-resume-card {
  width: 180px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
  overflow: hidden;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  cursor: pointer;
  flex-shrink: 0;
}

.pdf-resume-card:hover {
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2);
  border-color: #667eea;
  transform: translateY(-3px);
}

/* 卡片头部 */
.pdf-card-header {
  padding: 12px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e8e8e8;
}

.pdf-icon {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 6px;
  color: white;
  font-size: 20px;
}

.pdf-actions-icon {
  display: flex;
  gap: 4px;
}

.action-icon-btn {
  width: 28px;
  height: 28px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: white;
  color: #667eea;
  transition: all 0.3s ease;
}

.action-icon-btn:hover {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  transform: scale(1.1);
}

.action-icon-btn.el-button--danger {
  color: #f56c6c;
}

.action-icon-btn.el-button--danger:hover {
  background: #f56c6c;
  color: white;
}

/* 卡片主体 */
.pdf-card-body {
  padding: 12px;
  flex: 1;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.pdf-card-body:hover {
  background: #f8f9fa;
}

.pdf-title {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
}

.pdf-meta {
  margin: 0 0 4px 0;
  font-size: 12px;
  color: #667eea;
  font-weight: 500;
}

.pdf-date {
  margin: 0;
  font-size: 11px;
  color: #999;
}

/* 上传对话框样式 */
.upload-area {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  padding: 40px;
}

.el-icon--upload {
  font-size: 67px;
  color: #667eea;
  margin-bottom: 16px;
}

.el-upload__text {
  color: #666;
  font-size: 14px;
}

.el-upload__text em {
  color: #667eea;
  font-style: normal;
}

.el-upload__tip {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}

/* Empty 状态 */
:deep(.el-empty) {
  padding: 60px 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}

:deep(.el-empty__description) {
  margin-top: 16px;
}

/* 分页样式优化 */
:deep(.el-pagination) {
  font-weight: normal;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next),
:deep(.el-pagination .el-pager li) {
  background: transparent;
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-pagination .el-pager li:hover),
:deep(.el-pagination .btn-prev:hover),
:deep(.el-pagination .btn-next:hover) {
  background: #f0f0f0;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

/* 按钮样式 */
.el-button {
  border-radius: 6px;
  padding: 10px 20px;
}

/* 响应式 */
@media (max-width: 992px) {
  .my-resumes-container {
    padding: 12px;
  }
  
  .resume-section {
    min-height: auto;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .uploaded-resume-card {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .pdf-icon {
    margin-right: 0;
  }
  
  .resume-actions {
    width: 100%;
    justify-content: flex-start;
  }
}
</style>

